package cn.hiapi.shopkeeper.service.order;

import cn.hiapi.basic.ResUtils;
import cn.hiapi.basic.exception.BasicException;
import cn.hiapi.basic.jpa.pageable.QueryWrapper;
import cn.hiapi.basic.pay.IPaySuccessCallback;
import cn.hiapi.basic.pay.model.SuccessModel;
import cn.hiapi.basic.redis.data.LockConst;
import cn.hiapi.basic.redis.service.RedisService;
import cn.hiapi.basic.service.AbsBasicService;
import cn.hiapi.basic.token.enums.TokenType;
import cn.hiapi.interfaces.DispatchContext;
import cn.hiapi.interfaces.ILockService;
import cn.hiapi.interfaces.config.IConfigService;
import cn.hiapi.interfaces.finance.IAmountService;
import cn.hiapi.interfaces.finance.IAssetsService;
import cn.hiapi.interfaces.finance.model.AmountChange;
import cn.hiapi.interfaces.user.IUserService;
import cn.hiapi.shop.entity.order.OrderComment;
import cn.hiapi.shop.service.order.IOrderCommentPlugins;
import cn.hiapi.shop.service.product.ProductNumService;
import cn.hiapi.shopkeeper.consts.AppConst;
import cn.hiapi.shopkeeper.entity.activity.Activity;
import cn.hiapi.shopkeeper.entity.activity.ActivityCodeRecord;
import cn.hiapi.shopkeeper.entity.activity.ActivityOther;
import cn.hiapi.shopkeeper.entity.activity.ActivitySolitaireItem;
import cn.hiapi.shopkeeper.entity.order.ActivityInviteRecord;
import cn.hiapi.shopkeeper.entity.order.ActivityOrder;
import cn.hiapi.shopkeeper.entity.order.ActivityOrderLog;
import cn.hiapi.shopkeeper.enums.ActivityType;
import cn.hiapi.shopkeeper.enums.OrderLogType;
import cn.hiapi.shopkeeper.enums.OrderStatus;
import cn.hiapi.shopkeeper.jpa.order.ActivityOrderJpa;
import cn.hiapi.shopkeeper.service.ShopkeeperNotifyService;
import cn.hiapi.shopkeeper.service.activity.*;
import cn.hiapi.shopkeeper.service.shopkeeper.ShopUserService;
import cn.hiapi.utils.JsonUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;

/**
 * @author AdinZ
 * @date 2022/12/17 13:35
 */
@Service
@Slf4j
public class ActivityOrderService extends AbsBasicService<ActivityOrderJpa, ActivityOrder, Long> implements IPaySuccessCallback, IOrderCommentPlugins, IActivityStatusEvent {

    private final DispatchContext dispatchContext;

    public ActivityOrderService(DispatchContext dispatchContext) {
        this.dispatchContext = dispatchContext;
    }

    @Override
    public String getType() {
        return AppConst.PAY_CALL_TYPE_ORDER;
    }

    @Override
    public ActivityOrder save(ActivityOrder activityOrder) {
        activityOrder.calculate();
        this.dispatchContext.getServiceOne(ShopUserService.class).createUser(activityOrder.getShopId(), activityOrder.getBuyerId(), activityOrder.getAid());

        if (activityOrder.getStatus() == OrderStatus.WAIT_USE || activityOrder.getStatus() == OrderStatus.WAIT_GROUP) {
            activityOrder.setOrderType(1);
        }

        if (activityOrder.getStatus() == OrderStatus.CLOSE || activityOrder.getStatus() == OrderStatus.GROUP_FAIL) {
            activityOrder.setOrderType(0);
        }
        if (activityOrder.getActivityType() == ActivityType.LOTTERY || activityOrder.getActivityType() == ActivityType.LOTTERY_AD) {
            activityOrder.setPayment(BigDecimal.ZERO);
        }
        if (activityOrder.getStatus() == OrderStatus.WAIT_COMMENT || activityOrder.getStatus() == OrderStatus.COMPLETE) {
            activityOrder.setUseStatus(1);
            activityOrder.setUseTime(System.currentTimeMillis());
        } else activityOrder.setUseStatus(0);
        return super.save(activityOrder);
    }

    @Override
    public ActivityOrder update(ActivityOrder activityOrder) {
        return this.save(activityOrder);
    }

    @Override
    @Transactional
    public boolean payCallback(SuccessModel model) throws BasicException {
        String lock = LockConst.getLock("order-callback", model.getFid());
        try {
            this.dispatchContext.getServiceOne(ILockService.class).lockThr(lock);
            ActivityOrder order = this.get(model.getFid());
            if (order == null) throw new BasicException("订单不存在");
            if (order.getStatus() != OrderStatus.WAIT_PAY) throw new BasicException("订单状态不正确");
            order.setUpdated(System.currentTimeMillis());
            if (order.getActivityType() == ActivityType.GROUP && order.getFid() != null)
                order.setStatus(OrderStatus.WAIT_GROUP);
            else order.setStatus(OrderStatus.WAIT_USE);
            order.setStatusType(1);
            order.setPayType(model.getPayType());
            order.setPayTime(System.currentTimeMillis());
            this.save(order);
            if (order.getActivityType() == ActivityType.GROUP && order.getFid() != null) {
                this.dispatchContext.getServiceOne(ActivityGroupOrderService.class).dispatch(order.getFidType(), order.getFid());
            } else if (order.getActivityType() == ActivityType.CARD) {
                this.dispatchContext.getServiceOne(ActivityCardOrderService.class).payCallback(order);
            }
            if (order.getActivityType() != ActivityType.CARD && order.getActivityType() != ActivityType.GROUP) {
                //非次卡活动,都创建一个 激活码
                this.dispatchContext.getServiceOne(ActivityCodeRecordService.class).createCode(order);
            }
            this.dispatchContext.getServiceOne(MyActivityOrderService.class).payCallback(order);
            if (order.getActivityType() == ActivityType.SOLITAIRE) {
                this.dispatchContext.getServiceOne(ActivitySolitaireOrderService.class).payCallback(order);
            } else if (order.getActivityType() == ActivityType.BARGAIN) {
                this.dispatchContext.getServiceOne(ActivityBargainOrderService.class).payCallback(order);
            }
            //更新销量
            this.dispatchContext.getServiceOne(ProductNumService.class).addNumber(order.getAid(), AppConst.ACTIVITY_SELL_TOTAL, order.getNumber());
            this.dispatchContext.getServiceOne(ShopkeeperNotifyService.class).orderNotify(ShopkeeperNotifyService.OrderNotifyType.PAYMENT, order);

            ActivityOther other = this.dispatchContext.getServiceOne(ActivityOtherService.class).getByAid(order.getAid());
            if (other != null) {
                if (other.getGiftSugar() != null && other.getGiftSugar().compareTo(BigDecimal.ZERO) > 0) {
                    this.dispatchContext.getServiceOne(IAssetsService.class).changeAmount(AmountChange.builder()
                            .mid(0).fid(order.getBuyerId()).fidType(TokenType.ROLE_USER)
                            .amount(other.getGiftSugar()).type(AppConst.FINANCE_AMOUNT_SUGAR)
                            .sourceType(AppConst.FINANCE_INCOME_SOURCE_ACTIVITY_GIFT).sourceId(order.getId())
                            .title(order.getTitle() + " 赠送").remark(order.getTitle() + "赠送")
                            .build());
                }
                if (order.getInviteUid() != null && other.getShare() == 1 && other.getShareAmount() != null && other.getShareAmount().compareTo(BigDecimal.ZERO) > 0) {
                    ActivityInviteRecord record = new ActivityInviteRecord();
                    record.setAid(order.getAid());
                    record.setUid(order.getBuyerId());
                    record.setInviteUid(order.getInviteUid());
                    record.setType(order.getActivityType());
                    record.setShopId(order.getShopId());
                    record.setStatus(1);
                    this.dispatchContext.getServiceOne(ActivityFactory.class).get(record.getType()).inviteNewUser(record, other);
                    this.dispatchContext.getServiceOne(ActivityInviteRecordService.class).save(record);
                }


            }


            return true;
        } finally {
            this.dispatchContext.getServiceOne(ILockService.class).unlock(lock);
        }
    }


    /**
     * 关闭订单
     *
     * @param id
     */
    @Transactional
    public void closeOrder(long id) {
        ActivityOrder order = this.get(id);
        if (order == null) throw new BasicException("订单不存在");
        this.closeOrder(order);
    }


    public void closeOrder(ActivityOrder order) {
        if (order.getStatus() != OrderStatus.WAIT_PAY) throw new BasicException("订单状态错误");
        order.setStatus(OrderStatus.CLOSE);
        order.setUpdated(System.currentTimeMillis());
        this.update(order);
        this.dispatchContext.getServiceOne(ShopkeeperNotifyService.class).orderNotify(ShopkeeperNotifyService.OrderNotifyType.CLOSE, order);
        this.dispatchContext.getServiceOne(ProductNumService.class).addNumber(order.getAid(), AppConst.ACTIVITY_SELL_TOTAL, order.getNumber());
        if (order.getActivityType() == ActivityType.GROUP && order.getFid() != null) {
            this.dispatchContext.getServiceOne(ActivityGroupOrderService.class).dispatch(AppConst.GROUP_CLOSE, order.getFid());
            this.dispatchContext.getServiceOne(ShopkeeperNotifyService.class).orderNotify(ShopkeeperNotifyService.OrderNotifyType.GROUP_FAIL, order);
        }
        if (order.getSugar().compareTo(BigDecimal.ZERO) > 0) {
            this.dispatchContext.getServiceOne(IAssetsService.class).changeAmount(
                    AmountChange.builder()
                            .fid(order.getBuyerId()).fidType(TokenType.ROLE_USER).mid(0)
                            .type(AppConst.FINANCE_AMOUNT_SUGAR).amount(order.getSugar())
                            .sourceId(order.getId()).sourceType(AppConst.PAY_CALL_TYPE_ORDER)
                            .remark(order.getTitle() + " - 订单关闭").title(order.getTitle() + " - 订单关闭")
                            .build()
            );
        }

    }

    /**
     * 成团成功
     *
     * @param gid
     */
    @Transactional
    public void groupSuccess(long gid) {
        List<ActivityOrder> list = this.findList(new QueryWrapper().eq("fid", gid).eq("status", OrderStatus.WAIT_GROUP));
        list.forEach(e -> {
            e.setStatus(OrderStatus.WAIT_USE);
            e.setUpdated(System.currentTimeMillis());
        });
        this.save(list);
        for (ActivityOrder order : list) {
            this.dispatchContext.getServiceOne(ActivityCodeRecordService.class).createCode(order);
            this.dispatchContext.getServiceOne(ShopkeeperNotifyService.class).orderNotify(ShopkeeperNotifyService.OrderNotifyType.GROUP_SUCCESS, order);
            this.dispatchContext.getServiceOne(MyActivityOrderService.class).payCallback(order);
        }
    }


    /**
     * 团购的用户资料
     *
     * @param fid
     * @return
     */
    public List groupUserList(long fid, OrderStatus status) {
        QueryWrapper wrapper = new QueryWrapper().eq("fid", fid);
        if (status == null || status != OrderStatus.GROUP_FAIL)
            wrapper.eq("statusType", 1);
        else wrapper.eq("status", OrderStatus.GROUP_FAIL);
        List<ActivityOrder> orders = this.dispatchContext.getServiceOne(ActivityOrderService.class).findList(wrapper);
        List<JSONObject> items = orders.stream().map(e -> {
            Object base = this.dispatchContext.getServiceOne(IUserService.class).fieldBase(e.getBuyerId());
            if (base != null) {
                JSONObject user = JSON.parseObject(JSON.toJSONString(base));
                if (StringUtils.equalsIgnoreCase(e.getFidType(), AppConst.GROUP_NEW)) {
                    user.put("captain", true);
                }
                return user;
            } else return null;
        }).collect(Collectors.toList());

        return items;
    }

    /**
     * 评论校验 修改订单状态
     *
     * @param uid
     * @param comments
     */
    @Override
    @Transactional
    public void comment(long uid, List<OrderComment> comments) {
        comments.forEach(e -> {
            ActivityOrder order = this.get(e.getOid());
            if (order == null || order.getBuyerId() != uid) throw new BasicException("订单不存在");
            if (order.getStatus() != OrderStatus.WAIT_COMMENT) throw new BasicException("订单状态错误");
            e.setShopId(order.getShopId());
            e.setMid(0);
            e.setGid(order.getAid());
            order.setStatus(OrderStatus.COMPLETE);
            order.setUpdated(System.currentTimeMillis());
            this.save(order);
            this.dispatchContext.getServiceOne(ShopkeeperNotifyService.class).orderNotify(ShopkeeperNotifyService.OrderNotifyType.COMMENT, order);
        });
    }


    /**
     * 接龙活动结束 进行退费处理
     * 接龙结束,结算订单
     *
     * @param aid
     */
    @Transactional
    public void solitaireOrderEnd(long aid) {
        log.info("[接龙活动] 接龙活动停止, 进行订单退款处理 aid:" + aid);

        List<ActivitySolitaireItem> items = this.dispatchContext.getServiceOne(ActivitySolitaireItemService.class).listByAid(aid);
        if (items.isEmpty()) {
            log.info("[接龙活动] 本活动:{} 没有返现活动,跳过", aid);
            return;
        }
        //查询 接龙订单, 实付金额的, 和 已经使用的 订单 进行返现
        List<ActivityOrder> list = findList(new QueryWrapper()
                .eq("aid", aid).eq("activityType", ActivityType.SOLITAIRE)
                .eq("statusType", 1));

        Map<Long, List<ActivityOrder>> listMap = list.stream().collect(Collectors.groupingBy(ActivityOrder::getBuyerId));

        log.info("[接龙活动] 活动结束:{} 计算折扣,订单数:{}  参与用户数:{}", aid, list.size(), listMap.size());

        Optional<ActivitySolitaireItem> optional = items.stream().filter(e -> e.getCount() <= listMap.size()).sorted(Comparator.comparing(ActivitySolitaireItem::getCount).reversed()).findFirst();
        if (!optional.isPresent()) {
            log.info("[接龙活动] 本活动:{} 没有符合条件的返现", aid);
            return;
        }

        ActivitySolitaireItem item = optional.get();
        log.info("[接龙活动] 活动结束:{} 计算折扣,订单数:{}  参与用户数:{}", aid, list.size(), listMap.size());

        for (ActivityOrder order : list) {
            if (item.getRate().compareTo(BigDecimal.TEN) >= 0) {
                log.info("[接龙活动] 本活动:{} 折扣为10 跳过计算", aid);
                continue;
            }
            if (item.getRate().compareTo(BigDecimal.ZERO) <= 0) {
                log.info("[接龙活动] 本活动:{} 折扣为0 跳过计算", aid);
                continue;
            }

            BigDecimal multiply = order.getPayment().multiply(item.getRate().divide(BigDecimal.valueOf(10), 4, RoundingMode.HALF_EVEN));

            if (multiply.compareTo(BigDecimal.ZERO) <= 0) {
                log.info("[接龙活动] 本活动:{} 折扣金额 低于0 跳过计算", aid);
                continue;
            }
            order.setSolitaire(order.getPayment().subtract(multiply));
            order.setUpdated(System.currentTimeMillis());
            this.save(order);

            //活动结束后,进行折扣结算
            this.dispatchContext.getServiceOne(IAssetsService.class).changeAmount(AmountChange.builder()
                    .fid(order.getBuyerId()).fidType(TokenType.ROLE_USER).mid(0)
                    .type(AppConst.FINANCE_AMOUNT_MONEY).amount(order.getPayment().subtract(multiply))
                    .title("接龙返现 折扣" + item.getRate() + " - " + order.getTitle()).remark("接龙返现 折扣:" + item.getRate() + " 订单数:" + list.size() + " 参与人数:" + listMap.size() + " - " + order.getTitle())
                    .sourceId(order.getId()).sourceType(AppConst.PAY_CALL_TYPE_ORDER)
                    .build());

            this.dispatchContext.getServiceOne(ActivityOrderLogService.class).systemLog(order.getId(), "接龙结束 给用户折扣返现:" + order.getPayment().subtract(multiply) + "   折扣:" + item.getRate() + " 订单数:" + list.size() + " 参与人数:" + listMap.size() + " - " + order.getTitle());

            if (order.getStatus() == OrderStatus.WAIT_USE) {
                log.info("[接龙活动] 本活动:{} 订单还未核销,跳过给商户结算", aid);
                continue;
            }

            this.orderSettle(order);
        }
    }


    /**
     * 活动结束,
     *
     * @param list
     */
    @Override
    public void activityChange(List<Activity> list) {
        for (Activity activity : list) {
            if (activity.getStatus() == 2) {
                if (activity.getType() == ActivityType.SOLITAIRE)
                    this.solitaireOrderEnd(activity.getId());
            }
        }

    }

    @Override
    public void activityUseEnd(List<Activity> list) {
        for (Activity activity : list) {
            log.info("[活动兑换时间结束] 执行结束 活动id:{} 活动名字:{}", activity.getId(), activity.getTitle());
            this.activityOrderRefund(activity.getId());
        }
    }

    /**
     * 活动结束,待使用的订单进行退款操作
     *
     * @param aid
     */
    @Transactional
    public void activityOrderRefund(long aid) {

        //活动结束,待使用的订单,
        List<ActivityOrder> list = this.findList(new QueryWrapper().eq("aid", aid).eq("status", OrderStatus.WAIT_USE));

        log.info("[活动兑换时间结束]  活动结束, 未核销的订单进行退款 活动id:{} 退款订单数:{}", aid, list.size());

        for (ActivityOrder order : list) {
            order.setStatus(OrderStatus.REFUND);
            order.setUpdated(System.currentTimeMillis());
            this.dispatchContext.getServiceOne(ActivityOrderLogService.class).systemLog(order.getId(), "活动兑换时间到期,订单退款");

            if (order.getStatusType() == 1) {
                //活动结束后,进行折扣结算
                this.dispatchContext.getServiceOne(IAssetsService.class).changeAmount(AmountChange.builder()
                        .fid(order.getBuyerId()).fidType(TokenType.ROLE_USER).mid(0)
                        .type(AppConst.FINANCE_AMOUNT_MONEY).amount(order.getPayment().subtract(order.getSolitaire()))
                        .title("超时未核销退款 - " + order.getTitle()).remark("超时未核销退款 - " + order.getTitle())
                        .sourceId(order.getId()).sourceType(AppConst.PAY_CALL_TYPE_ORDER)
                        .build());
                this.dispatchContext.getServiceOne(ActivityOrderLogService.class).systemLog(order.getId(), "退余额" + order.getPayment().subtract(order.getSolitaire()) + "到用户余额中");
                log.info("[活动兑换时间结束]  活动结束, 执行退款 活动id:{} ", aid);
            }
            this.save(order);
            this.dispatchContext.getServiceOne(ActivityCodeRecordService.class).destroyCode(order.getId());
            this.dispatchContext.getServiceOne(ActivityOrderLogService.class).systemLog(order.getId(), "销毁全部兑换码");
            log.info("[活动兑换时间结束]  活动结束, 销毁兑换码 活动id:{} ", aid);
        }
    }

    /**
     * 核销订单
     *
     * @param oid
     */
    @Transactional
    public void checkOrder(long shopId, long oid) {
        ActivityOrder order = this.get(oid);
        if (order == null) throw new BasicException("订单不存在");
//        if (order.getStatus() != OrderStatus.WAIT_USE) throw new BasicException("订单状态错误");
        if (order.getShopId() != shopId) throw new BasicException("非本店订单");
        if (order.getUseStart() > System.currentTimeMillis()) throw new BasicException("还没到兑换时间");
        if (order.getUseEnd() < System.currentTimeMillis()) throw new BasicException("兑换时间已经过去");


        ActivityOrderLog orderLog = new ActivityOrderLog();
        orderLog.setUserType(AppConst.USER_TYPE_SHOP);
        orderLog.setOid(oid);
        orderLog.setType(OrderLogType.ORDER_CHECK);
        orderLog.setRemark("订单核销");
        this.dispatchContext.getServiceOne(ActivityOrderLogService.class).save(orderLog);
        this.dispatchContext.getServiceOne(ShopkeeperNotifyService.class).orderNotify(ShopkeeperNotifyService.OrderNotifyType.ORDER_USE, order);
        final OrderStatus status = order.getStatus();
        if (status == OrderStatus.WAIT_USE) {
            order.setStatus(OrderStatus.WAIT_COMMENT);
            order.setUseTime(System.currentTimeMillis());
        }
        this.save(order);

        if (order.getStatusType() != 1) {
            log.info("[订单核销] 免费订单,不进行结算 订单id:{}", oid);
            this.dispatchContext.getServiceOne(ActivityOrderLogService.class).systemLog(order.getId(), "免费订单,不进行结算");
            return;
        }
        if (order.getActivityType() == ActivityType.SOLITAIRE) {
            log.info("[订单核销] [接龙订单] 核销时不结算给商家 订单id:{}", order.getId());
            this.dispatchContext.getServiceOne(ActivityOrderLogService.class).systemLog(order.getId(), "[接龙订单] 核销时不结算给商家");
            return;
        }
        //如果等于次卡,且第一次状态不是待使用, 跳过结算
        if (order.getActivityType() == ActivityType.CARD && status != OrderStatus.WAIT_USE) {
            return;
        }

        this.orderSettle(order);
    }


    void orderSettle(ActivityOrder order) {


        JSONObject config = this.dispatchContext.getServiceOne(IConfigService.class).getConfig(0, AppConst.CONFIG_SHOPKEEPER_CONFIG);
        BigDecimal shopRate = JsonUtils.getBigDecimal(config, "shop_rate");
        if (order.getSolitaire() == null || order.getSolitaire().compareTo(BigDecimal.ZERO) < 0)
            order.setSolitaire(BigDecimal.ZERO);
        //平台手续费       平台手续费率  >0     平台手续费率/100* 支付金额  否则返回0
        BigDecimal payment = order.getPayment().subtract(order.getSolitaire());
        BigDecimal fee = shopRate.compareTo(BigDecimal.ZERO) > 0 ? shopRate.divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_EVEN).multiply(payment) : BigDecimal.ZERO;
        log.info("[订单核销] 结算金额 店铺:{}-{}  平台:{}  订单id:{}", order.getShopId(), payment.subtract(fee), fee, order.getId());
        this.dispatchContext.getServiceOne(ActivityOrderLogService.class).systemLog(order.getId(), "[接龙订单] 给商家结算 余额:" + payment.subtract(fee));
        //给店铺结算
        this.dispatchContext.getServiceOne(IAssetsService.class).changeAmount(AmountChange.builder()
                .mid(0).fid(order.getShopId()).fidType(AppConst.FID_TYPE_SHOP)
                .type(AppConst.FINANCE_AMOUNT_MONEY).amount(payment.subtract(fee))
                .sourceId(order.getId()).sourceType(this.getType())
                .title("核销订单:" + order.getTitle()).remark("核销订单:" + order.getTitle())
                .build());

        if (fee.compareTo(BigDecimal.ZERO) > 0) {

            //给平台结算手续费
            this.dispatchContext.getServiceOne(IAssetsService.class).changeAmount(AmountChange.builder()
                    .mid(0).fid(AppConst.PLATFORM_UID).fidType(AppConst.FID_TYPE_PLATFORM)
                    .type(AppConst.FINANCE_AMOUNT_MONEY).amount(fee)
                    .sourceId(order.getId()).sourceType(this.getType())
                    .title("核销订单:" + order.getTitle()).remark("核销订单:" + order.getTitle())
                    .build());
            this.dispatchContext.getServiceOne(ActivityOrderLogService.class).systemLog(order.getId(), "[接龙订单] 给平台结算 余额:" + fee);

        }

        if (order.getSugar().compareTo(BigDecimal.ZERO) > 0) {
            BigDecimal sugarFee = shopRate.compareTo(BigDecimal.ZERO) > 0 ? shopRate.divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_EVEN).multiply(order.getSugar()) : BigDecimal.ZERO;
            this.dispatchContext.getServiceOne(IAssetsService.class).changeAmount(AmountChange.builder()
                    .mid(0).fid(order.getShopId()).fidType(AppConst.FID_TYPE_SHOP)
                    .type(AppConst.FINANCE_AMOUNT_SUGAR).amount(order.getSugar().subtract(sugarFee))
                    .sourceId(order.getId()).sourceType(this.getType())
                    .title("核销订单:" + order.getTitle()).remark("核销订单:" + order.getTitle())
                    .build());
            this.dispatchContext.getServiceOne(ActivityOrderLogService.class).systemLog(order.getId(), "[接龙订单] 给商家结算 喜糖:" + order.getSugar().subtract(sugarFee));

            if (sugarFee.compareTo(BigDecimal.ZERO) > 0) {
                //给平台结算手续费
                this.dispatchContext.getServiceOne(IAssetsService.class).changeAmount(AmountChange.builder()
                        .mid(0).fid(AppConst.PLATFORM_UID).fidType(AppConst.FID_TYPE_PLATFORM)
                        .type(AppConst.FINANCE_AMOUNT_SUGAR).amount(sugarFee)
                        .sourceId(order.getId()).sourceType(this.getType())
                        .title("核销订单:" + order.getTitle()).remark("核销订单:" + order.getTitle())
                        .build());
                this.dispatchContext.getServiceOne(ActivityOrderLogService.class).systemLog(order.getId(), "[接龙订单] 给平台结算 喜糖:" + sugarFee);
            }
        }


    }

    /**
     * 购买用户数量
     *
     * @param aid
     * @return
     */
    public long totalBuyUser(long aid) {
        return ResUtils.getDefault(this.repository.totalBuyUser(aid).size());
    }

    public BigDecimal totalMoney(long aid) {
        return ResUtils.getDefault(this.repository.totalMoney(aid));
    }

    /**
     * 统计时间范围内支付的金额
     *
     * @param shopId
     * @param startTime
     * @param endTime
     * @return
     */
    public BigDecimal totalMoney(long shopId, long startTime, long endTime) {
        return ResUtils.getDefault(this.repository.totalMoney(shopId, startTime, endTime));
    }

    /**
     * 统计时间范围内订单数量
     *
     * @param shopId
     * @param startTime
     * @param endTime
     * @return
     */
    public long totalCount(long shopId, long startTime, long endTime) {
        return this.count(new QueryWrapper().eq("shopId", shopId).between("created", startTime, endTime)
                .eq("orderType", 1));
    }

    /**
     * 时间范围内支付用户数
     *
     * @param shopId
     * @param startTime
     * @param endTime
     * @return
     */
    public long totalBuyUser(long shopId, long startTime, long endTime) {
        return ResUtils.getDefault(this.repository.totalBuyUser(shopId, startTime, endTime).size());
    }


    /**
     * 统计 接龙返现金额
     *
     * @param aid
     * @return
     */
    public BigDecimal totalSumSolitaire(long aid) {
        BigDecimal amount = repository.totalSumSolitaire(aid);
        return ResUtils.getDefault(amount);
    }

    /**
     * 统计待核销订单金额
     *
     * @param shopId
     * @return
     */
    public BigDecimal totalSumWaitUseAmount(long shopId) {
        return ResUtils.getDefault(this.repository.totalSumWaitUseAmount(shopId));
    }


    /**
     * 统计已核销订单金额
     *
     * @param shopId
     * @return
     */
    public BigDecimal totalSumComplete(long shopId) {
        return ResUtils.getDefault(this.repository.totalSumComplete(shopId));
    }
}
